package de.chessgame.gamelogic.piece;

import java.util.ArrayList;

import de.chessgame.gamelogic.Coordinate;

public class Pawn extends Piece {

	private final int BOARD_SIZE = 8;

	public Pawn(Fraction fraction) {
		super(Type.PAWN, fraction);
	}

	@Override
	public void calculatePossibleMoves(Piece[][] content, int xOld, int yOld, boolean inCheck) {
		possibleMoves.clear();
		super.calculatePossibleMoves(content, xOld, yOld, inCheck);
		possibleMoves.addAll(givePossibleMovesForPawn(content, xOld, yOld));
	}
	
	@Override
	public boolean canMove(Piece[][] content, int xOld, int yOld, boolean inCheck) {
		return givePossibleMovesForPawn(content, xOld, yOld).size() != 0;
	}

	private ArrayList<Coordinate> givePossibleMovesForPawn(Piece[][] content, int xOld, int yOld) {
		ArrayList<Coordinate> list = new ArrayList<Coordinate>();
		int yDirection = fraction == Fraction.WHITE ? -1 : 1;

		if (content[yOld + yDirection][xOld] == null) {
			list.add(new Coordinate(xOld, yOld + yDirection));
			if (moveCount == 0 && content[yOld + 2 * yDirection][xOld] == null) {
				list.add(new Coordinate(xOld, yOld + 2 * yDirection));
			}
		}

		for (int xTry = xOld - 1, yTry = yOld + yDirection, i = 0; i < 2; xTry = xOld + 1, i++) {
			if (isSquareOnBoard(content, xTry, yTry)
					&& content[yTry][xTry] != null
					&& content[yTry][xTry].getFraction() != fraction) {
				list.add(new Coordinate(xTry, yTry));
			}
		}
		list = removeIrregularyMoves(content, list, xOld, yOld);
		return list;
	}

	@Override
	public boolean onMove(Piece[][] content, int xOld, int yOld, int x, int y) {
		super.onMove(content, xOld, yOld, x, y);

		if ((fraction == Fraction.WHITE && y == 0)
				|| (fraction == Fraction.BLACK && y == BOARD_SIZE - 1)) {
			content[y][x] = Piece.transformPiece(content[y][x], null);
			return true;
		}
		return false;
	}

}
